<template>
  <div v-loading.fullscreen.lock="fullscreenLoading">
    <div class="org-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>产品信息管理</el-breadcrumb-item>
        <el-breadcrumb-item>详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div>
      <el-card class="box-card">
        <div slot="header" class="header">
          <div>基本信息</div>
          <div>
            <template v-if="baseInfoEditing">
              <el-button type="text" @click="cancelBaseInfo">放弃</el-button>
              <el-button type="text" @click="saveBaseInfo">保存</el-button>
            </template>
            <template v-else>
              <el-button type="text" @click="baseInfoEditing=true">编辑</el-button>
            </template>
          </div>
        </div>
        <div>
          <template v-if="baseInfoEditing">
            <div class="baseInfo-container">
              <el-upload
                class="avatar-uploader-production"
                :action="uploadUrl"
                :data="uploadConfig"
                :on-progress="() => setLoading(true)"
                name="file"
                :show-file-list="false"
                :multiple="false"
                :on-success="handleAvatarSuccess">
                <img v-if="newData.product.productMainImage" :src="`http://${newData.product.productMainImage}`" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-production-icon"></i>
              </el-upload>
              <el-form ref="baseInfoForm" :model="newData.product" label-width="120px">
                <el-form-item size="mini" label="产品名称" prop="productName">
                  <el-input v-model="newData.product.productName"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="行业/品类">
                  <el-input :value="getCategoryStr" disabled></el-input>
                </el-form-item>
                <el-form-item size="mini" label="系列" prop="productSeries">
                  <el-input v-model="newData.product.productSeries"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="型号" prop="productCode">
                  <el-input v-model="newData.product.productCode"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="建议价" prop="guidePrice">
                  <el-input v-model="newData.product.guidePrice"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </template>
          <template v-else>
            <div class="baseInfo-container">
              <img v-if="newData.product.productMainImage" :src="`http://${newData.product.productMainImage}`" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-production-icon"></i>
              <el-form ref="baseInfoForm" :model="newData.product" disabled label-width="120px">
                <el-form-item size="mini" label="产品名称" prop="productName">
                  <el-input v-model="newData.product.productName"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="行业/品类">
                  <el-input :value="getCategoryStr" disabled></el-input>
                </el-form-item>
                <el-form-item size="mini" label="系列" prop="productSeries">
                  <el-input v-model="newData.product.productSeries"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="型号" prop="productCode">
                  <el-input v-model="newData.product.productCode"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="建议价" prop="guidePrice">
                  <el-input v-model="newData.product.guidePrice"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </div>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="header">
          <div>尺寸规格 SKU</div>
          <div>
            <template v-if="SKUEditing">
              <el-button type="text" @click="cancelSKU">放弃</el-button>
              <el-button type="text" @click="saveSKU">保存</el-button>
            </template>
            <template v-else>
              <el-button type="text" @click="setSKUEditing">编辑</el-button>
            </template>
          </div>
        </div>
        <div>
          <template v-if="SKUEditing">
            <div class="SKU-container">
              <div class="SKU-item" v-for="item in newData.skuList">
                <div class="SKU-inline-form" v-for="skuAttr in item.skuAttributes">
                  <span class="SKU-label">{{ getSKUNameById(skuAttr.attributeId) }}</span>
                  <el-input size="mini" v-model="skuAttr.attributeSku"></el-input>
                </div>
                <div class="SKU-inline-form">
                  <span class="SKU-label">价格</span>
                  <el-input size="mini" v-model="item.skuPrice"></el-input>
                </div>
                <div class="SKU-inline-form">
                  <span class="SKU-label">SKU号</span>
                  <el-input size="mini" v-model="item.skuCode"></el-input>
                </div>
                <div class="SKUImage">
                  <el-upload
                    class="avatar-uploader-production"
                    :action="uploadUrl"
                    :data="uploadConfig"
                    :on-progress="() => setLoading(true)"
                    name="file"
                    :show-file-list="false"
                    :multiple="false"
                    :on-success="data => updateSKUItem(data, item)">
                    <img v-if="item.imageUrl" :src="`http://${item.imageUrl}`" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-production-icon"></i>
                  </el-upload>
                </div>
              </div>
              <div class="SKU-item">
                <div class="add-SKU" @click="addSKU">
                  添加SKU
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="SKU-container">
              <div class="SKU-item" v-for="item in newData.skuList">
                <div class="SKUImage">
                  <img v-if="item.imageUrl" :src="getImageUrl(item.imageUrl)" class="avatar">
                </div>
                <div class="SKU-inline-form" v-for="skuAttr in item.skuAttributes">
                  <span class="SKU-label">{{ getSKUNameById(skuAttr.attributeId) }}</span>
                  <el-input size="mini" disabled v-model="skuAttr.attributeSku"></el-input>
                </div>
                <div class="SKU-inline-form">
                  <span class="SKU-label">价格</span>
                  <el-input size="mini" disabled v-model="item.skuPrice"></el-input>
                </div>
                <div class="SKU-inline-form">
                  <span class="SKU-label">SKU号</span>
                  <el-input size="mini" disabled v-model="item.skuCode"></el-input>
                </div>
              </div>
            </div>
          </template>
        </div>
      </el-card>
      <el-card class="box-card" v-for="(item, index) in configData.cpsrList">
        <div slot="header" class="header">
          <div>{{ item.specificationName }}</div>
          <div>
            <template v-if="getDetailInfoEditing(index)">
              <el-button type="text" @click="cancelDetailInfo(item, index)">放弃</el-button>
              <el-button type="text" @click="saveDetailInfo(item, index)">保存</el-button>
            </template>
            <template v-else>
              <el-button type="text" @click="setDetailInfoEditing(index)">编辑</el-button>
            </template>
          </div>
        </div>
        <div>
          <template v-if="detailInfoEditing[index]">
            <div class="detail-container">
              <template v-if="item.level === 3">
                <div class="detail-item" v-for="level2Item in item.children">
                  <div class="detail-header">{{ level2Item.specificationName }}</div>
                  <div class="detail-inline-form" v-for="level3Item in level2Item.children">
                    <span class="detail-label">{{ level3Item.specificationName }}</span>
                    <el-input
                      size="mini"
                      :value="getDetailInfoValue(level3Item.specificationId)"
                      @change="value => setDetailInfoValue(level3Item.specificationId, value)"
                    ></el-input>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="detail-item">
                  <div class="detail-inline-form" v-for="level2Item in item.children">
                    <span class="detail-label">{{ level2Item.specificationName }}</span>
                    <el-input
                      size="mini"
                      :value="getDetailInfoValue(level2Item.specificationId)"
                      @change="value => setDetailInfoValue(level2Item.specificationId, value)"
                    ></el-input>
                  </div>
                </div>
              </template>
            </div>
          </template>
          <template v-else>
            <div class="detail-container">
              <template v-if="item.level === 3">
              <div class="detail-item" v-for="level2Item in item.children">
                <div class="detail-header">{{ level2Item.specificationName }}</div>
                <div class="detail-inline-form" v-for="level3Item in level2Item.children">
                  <span class="detail-label">{{ level3Item.specificationName }}</span>
                  <el-input
                    size="mini"
                    disabled
                    :value="getDetailInfoValue(level3Item.specificationId)"
                  ></el-input>
                </div>
              </div>
              </template>
              <template v-else>
                <div class="detail-item">
                  <div class="detail-inline-form" v-for="level2Item in item.children">
                    <span class="detail-label">{{ level2Item.specificationName }}</span>
                    <el-input
                      size="mini"
                      :value="getDetailInfoValue(level2Item.specificationId)"
                      disabled
                    ></el-input>
                  </div>
                </div>
              </template>
            </div>
          </template>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
  export default {
    name: "production-management-editor",
    data() {
      return ({
        fullscreenLoading: false,
        baseInfoEditing: false,
        SKUEditing: false,
        detailInfoEditing: {},
        categoryId: this.$route.params.categoryId,
        productId: this.$route.query.productId,
        productCode: this.$route.query.productCode || '',
        name: this.$route.query.name || '',
        originData: {
          product: {
            productCode: this.$route.query.productCode || '',
            productName: this.$route.query.name || '',
          },
          skuList: [],
          psList: [],
        },
        newData: {
          product: {
            productCode: this.$route.query.productCode || '',
            productName: this.$route.query.name || '',
          },
          skuList: [],
          psList: [],
        },
        configData: {
          csrList: [],
          cpsrList: [],
        },
        categoryTree: [],
        brandList: [],
        headerImageUrl: undefined,
        uploadUrl: '/file/uploadFile',
        uploadConfig: {
          type: 'Img'
        },
      })
    },
    computed: {
      getCategoryStr() {
        const categoryList = this.getPathByKey(+this.categoryId, 'id', this.categoryTree)
        return _.join(_.map(categoryList, item => item.categoryName), '>')
      },
    },
    mounted() {
      this.productId && this.getProductionOriginData()
      this.getConfigDataByCategoryId()
      this.getCategoryForEditor()
    },
    methods: {
      getProductionOriginData() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"Product_LoadData",
          "query":{
            productId: this.productId,
          }
        }).then(res => {
          loading.close()
          this.originData = _.cloneDeep(res.data.data)
          this.newData = res.data.data
        })
      },
      getConfigDataByCategoryId() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Product_GetPage",
          "query":{
            categoryId: this.categoryId,
          }
        }).then(res => {
          this.configData = res.data.data
        })
      },
      getCategoryForEditor() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Category_CategoryTree",
          "query":{}
        }).then(res => {
          this.categoryTree = res.data.data
        })
      },
      // getBrandList() {
      //   this.$http.post(this.GLOBAL.host, {
      //     "method":"Brand_List",
      //     "query":{}
      //   }).then(res => {
      //     this.
      // = res.data.data
      //   })
      // },
      getPathByKey(value, key, arr) {
        let temppath = [];
        try {
          function getNodePath(node){
            temppath.push(node);
            //找到符合条件的节点，通过throw终止掉递归
            if (node[key] === value) {
              throw ("GOT IT!");
            }
            if (node.children && node.children.length > 0) {
              for (var i = 0; i < node.children.length; i++) {
                getNodePath(node.children[i]);
              }

              //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
              temppath.pop();
            }
            else {

              //找到叶子节点时，删除路径当中的该叶子节点
              temppath.pop();
            }
          }
          for (let i = 0; i < arr.length; i++) {
            getNodePath(arr[i]);
          }
        } catch (e) {
          return temppath;
        }
      },
      getImageUrl(url) {
        return `http://${url}`
      },
      handleAvatarSuccess(data) {
        this.newData.product.productMainImage = data.fileUrl
        this.newData.product = _.clone(this.newData.product)
        this.setLoading()
      },
      cancelBaseInfo() {
        this.newData.product = _.clone(this.originData.product)
        this.$refs.baseInfoForm.resetFields()
        this.baseInfoEditing = false
      },
      saveBaseInfo() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"Product_AddAndUpdate",
          "data":{
            productId: this.productId,
            categoryId: this.categoryId,
            ...this.newData.product,
            creator: this.newData.creator || this.$store.state.user.id,
          }
        }).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.baseInfoEditing = false
            this.originData.product = _.cloneDeep(this.newData.product)
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            if (!this.productId) {
              this.productId = res.data.data.productId
              this.$router.replace({
                // path: `/organization/production-management/${data.categoryId}`,
                query: ({
                  productId: res.data.data.productId,
                })
              })
            }
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      setSKUEditing() {
        if (this.productId) {
          this.SKUEditing = true
        } else {
          this.$message({
            message: '请先填写并保存产品基本信息',
            type: 'warning'
          });
        }
      },
      getSKUNameById(id) {
        const SKUList = this.configData.csrList
        return _.get(_.find(SKUList, item => item.attributeId === id), 'attributeName')
      },
      cancelSKU() {
        this.newData.skuList = _.cloneDeep(this.originData.skuList)
        this.SKUEditing = false
      },
      saveSKU() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"ProductSku_AddAndUpdate",
          "data":{
            list: this.newData.skuList,
          }
        }).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.SKUEditing = false
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.refreshSKU()
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      refreshSKU() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Product_GetSku",
          "query":{
            productId: this.productId,
            categoryId: this.categoryId,
          }
        }).then(res => {
          if (res.data.code == 200) {
            this.originData.skuList = _.cloneDeep(res.data.data)
            this.newData.skuList = res.data.data
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      addSKU() {
        this.newData.skuList.push({
          creator:  this.$store.state.user.id,
          productId: this.productId,
          skuAttributes: this.configData.csrList.map(item => ({
            attributeId: item.attributeId,
            attributeSku: '',
          })),
          skuPrice: '',
          skuCode: '',
          imageUrl: ''
        })
      },
      updateSKUItem(data, item) {
        item.imageUrl = data.fileUrl
        this.newData.skuList = _.clone(this.newData.skuList)
        this.setLoading()
      },
      setDetailInfoEditing(id, value = true) {
        if (this.productId) {
          this.detailInfoEditing[id] = !!value
          this.detailInfoEditing = _.clone(this.detailInfoEditing)
        }
      },
      getDetailInfoEditing(id) {
        return this.detailInfoEditing[id]
      },
      saveDetailInfo(data, index) {
        const list = this.newData.psList.filter(item => {
          const dataPath = this.getPathByKey(item.specificationId, 'specificationId', data.children)
          return dataPath && dataPath.length > 0
        })
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"ProductSpecification_AddOrUpdate",
          "data":{
            list,
          }
        }).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.setDetailInfoEditing(index, false)
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.refreshOriginData()
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      refreshOriginData() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Product_LoadData",
          "query":{
            productId: this.productId,
          }
        }).then(res => {
          this.originData = res.data.data
        })
      },
      cancelDetailInfo(data, index) {
        this.newData.psList = _.cloneDeep(this.originData.psList)
        this.setDetailInfoEditing(index, false)
      },
      getDetailInfoValue(id) {
        return _.get(_.find(this.newData.psList, item => item.specificationId === id), 'specificationValue')
      },
      setDetailInfoValue(id, value) {
        const isModify = _.some(this.newData.psList, item => item.specificationId === id)
        if (isModify) {
          this.newData.psList = this.newData.psList.map(item => {
            if(item.specificationId === id) {
              return ({
                creator: this.$store.state.user.id,
                productId: this.productId,
                ...item,
                specificationValue: value,
              })
            }
            return item
          })
        } else {
          this.newData.psList = _.concat(this.newData.psList, ({
            specificationId: id,
            specificationValue: value,
            productId: this.productId,
          }))
        }
      },
      setLoading(flag = false){
        this.fullscreenLoading = flag
      }
    }
  }
</script>

<style lang="less" scoped>
  .org-breadcrumb {
    padding: 15px 0;
  }
  .container {
    padding: 20px;
    font-size: 16px;
  }
  .box-card {
    border: 1px solid #e0e8ef;
  }
  .header {
    background-color: #e8eef4;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
  }
  .baseInfo-container {
    display: flex;
  }
</style>
<style lang="less">
  .avatar-uploader-production .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-production .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-production-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-upload__input {
    display: none !important;
  }
  .SKU-container, .detail-container {
    display: flex;
    flex-wrap: wrap;
  }
  .SKU-item {
    width: 200px;
    flex: 200px 0 0;
    padding: 10px;
    min-height: 280px;
  }
  .SKU-inline-form, .detail-inline-form {
    display: flex;
    margin: 10px 0;
  }
  .SKU-label, .detail-label {
    flex: 100px 0 0;
  }
  .add-SKU {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #e8eef4;
    cursor: pointer;
    height: 100%;
  }
  .detail-item {
    width: 300px;
    flex: 30% 0 0;
    padding: 10px;
    min-height: 280px;
  }
  .detail-header {
    border: 1px solid #e8eef4;
    font-size: 16px;
    line-height: 30px;
  }
</style>
